<?php
/**
 * Created by Alan.
 * User: Alan
 * Date: 2018\10\7 0007
 * Time: 18:06
 */

namespace app\bis\controller;


use app\common\model\Bis;
use app\common\model\BisAccount;
use app\common\model\BisLocation;
use app\common\model\Category;
use app\common\model\City;
use app\common\validate\BisValidate;
use phpmailer\Email;
use think\Controller;
use think\Db;
use think\Exception;

class Register extends Controller
{
    public function index()
    {
        //获取一级城市数据
        $cities = City::getNormalCityByParentId(0);

        //获取一级栏目分类数据
        $categories = Category::getFirstCategorys();

        return $this->fetch('index', [
            'citys' => $cities,
            'categories' => $categories
        ]);
    }

    //新增数据
    public function add()
    {
        if(!request()->isPost()){
            return $this->error('非法请求');
        }

        $validate = (new BisValidate())->goCheck('add');
        if($validate !== true){
//            return $this->error($validate);
        }

        $data = input('post.');

        //获取商户地址经纬度
        $lntlat = \Map::getLatLng($data['address']);
        if(empty($lntlat) || $lntlat['status'] != 0 ){
            return $this->error('获取商户地址失败');
        }

        //查看用户是否存在
        $accountResult = (new BisAccount())->get(['username' => $data['username']]);
        if($accountResult){
            return $this->error('该用户存在，请重新分配');
        }

        Db::startTrans();
        try{
        //商户基本信息入库
        $bisData = [
            'name' => $data['name'],
            'city_id' =>$data['city_id'],
            'city_path' => empty($data['se_city_id'])?$data['city_id']:$data['city_id'].','.$data['se_city_id'],
            'logo' => $data['logo'],
            'licence_logo' => $data['licence_logo'],
            'bank_info' => $data['bank_info'],
            'bank_name' => $data['bank_name'],
            'bank_user' => $data['bank_user'],
            'faren'     => $data['faren'],
            'faren_tel' => $data['faren_tel'],
            'email'     => $data['email']
        ];
        $bisId = (new Bis())->add($bisData);
        if(!$bisId){
            throw new Exception('商户基础信息插入失败');
        }
        //总店相关信息入库
        $data['cat'] = '';
        if(!empty($data['se_category_id'])){
            $data['cat'] = implode('|', $data['se_category_id']);
        }

        $locationData = [
            'bis_id' => $bisId,
            'name' => $data['name'],
            'logo' => $data['logo'],
            'tel' => $data['tel'],
            'contact' => $data['contact'],
            'category_id' => $data['category_id'],
            'category_path' => $data['category_id'] . ',' . $data['cat'],
            'city_id' => $data['city_id'],
            'city_path' => empty($data['se_city_id']) ? $data['city_id'] : $data['city_id'].','.$data['se_city_id'],
            'api_address' => $data['address'],
            'open_time' => $data['open_time'],
            'content' => empty($data['content']) ? '' : $data['content'],
            'is_main' => 1,// 代表的是总店信息
            'xpoint' => empty($lnglat['result']['location']['lng']) ? '' : $lnglat['result']['location']['lng'],
            'ypoint' => empty($lnglat['result']['location']['lat']) ? '' : $lnglat['result']['location']['lat'],
        ];

        $locationId = (new BisLocation())->add($locationData);
        if(!$locationId){
            throw new Exception('总店相关信息插入失败');
        }
        //账户相关信息入库
        $data['code'] = mt_rand(100,10000);
        $accountData = [
            'bis_id' => $bisId,
            'username' => $data['username'],
            'code' => $data['code'],
            'password' => md5($data['password'].$data['code']),
            'is_main' => 1,
        ];

        $accountId = (new BisAccount())->add($accountData);
        if(!$accountId){
            throw new Exception('账户相关信息插入失败');
        }

        //发送邮件
       /* $url = request()->domain().url('bis/register/waiting',['id' => $bisId]);
        $title = "o2o入驻申请通知";
        $content = "您提交的入驻申请需要等待平台方审核；您可以通过点击链接<a href='".$url."' target='_blank'>查看链接</a>查看审核状态";
        \phpmailer\Email::send($data['email'],$title,$content);*/
        Db::commit();
        $this->success('申请成功',url('register/waiting',['id' => $bisId]));
        }catch (Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function waiting($id)
    {
       if(empty($id)){
            $this->error('error');
        }

        $detail = (new Bis())->get($id);
        return $this->fetch('',[
            'detail' => $detail
        ]);
    }
}